#! /bin/bash

##总说明
##编译该项目并发布到指定目录下
##运行改脚本请使用 sh -x build_prod.sh 或者 ./build_prod.sh
##如果出现权限不够 请使用 chmod +x build_prod.sh

#杀死8888对应的端口进程
d=`date "+%Y-%m-%d %H:%M:%S"`
st=`date -d "${d}" +%s`
echo "--------------------当前日期:${d}--------------------"

echo "--------------------拉取项目--------------------"
cd /home/devops/workspace/hotpot
git pull origin master
echo "--------------------拉取项目完成...--------------------"

port=9090

echo "--------------------端口:${port}--------------------"
java_ps_id=$(netstat -nlp | grep :${port} | awk '{print $7}' | awk -F"/" '{ print $1 }')

echo "--------------------Java进程id:${java_ps_id}--------------------"

if((java_ps_id>0)); then
 echo "-------------------->>杀死java进程:${java_ps_id}"
 kill -9 ${java_ps_id}
fi

jar_name="hotpot-gw-socket-assemble.jar"
echo "--------------------jar名称:${jar_name}"

jar_target="/home/devops/workspace/hotpot/hotpot-component-boot-starter-parent/hotpot-component-gateway-boot-starter-parent/hotpot-component-gateway-socket-boot-starter/target/"
echo "--------------------jar目录:${jar_target}"

jar_product="/home/devops/workspace/hotpot-gw-socket-deploy/"
echo "--------------------生产目录:${jar_product}"

mvn_exec="/home/devops/workspace/hotpot/"
echo "--------------------mvn执行路径:${mvn_exec}"


echo "--------------------开始构建项目--------------------"
cd ${mvn_exec}
mvnd clean package -DskipTests
echo "--------------------完成构建项目--------------------"


#清空发布目录的文件
echo "--------------------开始清除发布目录文件--------------------"
cd ${jar_product}
for file in ${jar_product}/*; do
  fileName=${file##*/}
  if [[ ${fileName} == *log* ]]; then
       echo "-------------------->跳过:${jar_product}${fileName}"
     else
       echo "-------------------->删除:${jar_product}${fileName}"
       rm -rf "${jar_product}${fileName}"
  fi
done
echo "--------------------清除发布目录文件完成--------------------"

echo "--------------------复制文件--------------------"
#复制编译好的文件到发布目录
cp -rf "${jar_target}${jar_name}" ${jar_product}

d=`date "+%Y-%m-%d %H:%M:%S"`
##计算耗时
ed=`date -d "${d}" +%s`
tt=$[ed-st]
fen=0
second=${tt}
if((tt>60));then
  fen=$[tt/60]
  second=$((tt%60))
fi

echo "--------------------启动java程序--------------------"

cd ${jar_product}
nohup java -jar ${jar_name} --spring.profiles.active=test  > log.file  2>&1 &

echo "--------------------完成:${d}--------------------"
echo "--------------------耗时:${fen}分${second}秒--------------------"